<template>
  <div class="ExhibitionInfoForm-container">
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      class="form"
      @submit.prevent="onSubmit"
    >
      <div class="title">视频上传</div>
      <el-form-item prop="videoFile">
        <div class="video-uploader">
          <video
            v-if="videoUrl && videoUrl.trim() !== ''"
            :src="videoUrl"
            class="video-preview"
            controls
            preload="metadata"
            @error="handleVideoError"
            @loadstart="handleVideoLoadStart"
            @canplay="handleVideoCanPlay"
          />
          <div v-else class="video-placeholder">
            <el-icon class="video-uploader-icon">
              <Plus />
            </el-icon>
            <div class="placeholder-text">
              {{
                props.mode === "view" ? "暂无视频" : "请点击下方按钮选择视频"
              }}
            </div>
          </div>
        </div>
        <input
          v-if="props.mode !== 'view'"
          ref="fileInput"
          type="file"
          accept="video/*"
          style="display: none"
          @change="handleFileChange"
        />
      </el-form-item>

      <el-form-item prop="videoName">
        <el-input
          v-model="form.videoName"
          placeholder="请输入视频名称"
          style="width: 400px"
          :disabled="props.mode === 'view'"
          :class="{ 'view-mode-input': props.mode === 'view' }"
          @input="handleVideoNameInput"
          @paste="handleVideoNamePaste"
          @keypress="handleVideoNameKeypress"
        />
      </el-form-item>

      <el-form-item style="margin: 20px 0">
        <el-button
          v-if="props.mode !== 'view'"
          size="large"
          type="success"
          @click="triggerFileUpload"
        >
          上传视频
        </el-button>
        <el-button v-if="props.mode === 'edit'" size="large" @click="onSubmit">
          修改
        </el-button>
        <el-button v-if="props.mode === 'add'" size="large" @click="onSubmit">
          提交
        </el-button>
      </el-form-item>
      <div class="bottom">
        <div class="bottom-down">
          上传格式：MP4、MOV、AVI，文件大小不超过50MB
        </div>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import { Plus } from "@element-plus/icons-vue";
import type { UploadFile, UploadFiles } from "element-plus";
import { ElMessage } from "element-plus";
import { uploadVideo, uploadVideoFile, updateVideo } from "@/api/videoInfo";
import {
  validateUploadFile,
  FileType,
  updateUploadConfig
} from "@/utils/uploadFile";
import {
  videoFormRules,
  validateVideoForm,
  validateVideoFile
} from "./utils/validation";
import { getExhibitorId } from "@/utils/getExhibitorId";

interface Props {
  mode?: "add" | "view" | "edit";
  formData?: any;
}

const props = withDefaults(defineProps<Props>(), {
  mode: "add",
  formData: () => ({})
});

const emit = defineEmits(["cancel", "confirm"]);

// 表单引用
const formRef = ref();

// 表单验证规则
const formRules = videoFormRules;

const form = ref({
  id: 0,
  exhibitor_id: getExhibitorId() || 0,
  videoName: "",
  videoFile: "" as string, // 保持这个字段名用于表单绑定
  video_url: "" as string, // 添加这个字段名用于数据映射
  status: 3 // 默认状态为待提交
});

// 预览地址（需在 watch 使用前声明，避免立即执行时未初始化）
const videoUrl = ref("");

// 处理视频URL的函数
const processVideoUrl = (url: string) => {
  if (!url) return "";

  console.log("处理视频URL:", url);

  // 如果是完整URL，直接使用
  if (url.startsWith("http")) {
    console.log("完整URL，直接使用:", url);
    return url;
  }

  // 使用OSS域名拼接
  const BASE_URL = "https://exhibition-bucket.oss-cn-beijing.aliyuncs.com";
  const processedUrl = `${BASE_URL}${url}`;
  console.log("使用OSS域名拼接:", processedUrl);
  return processedUrl;
};

// 监听props.formData变化，更新form数据
watch(
  () => props.formData,
  newData => {
    if (newData && Object.keys(newData).length > 0) {
      form.value = { ...newData };
      // 如果有视频URL，设置预览
      if (newData.video_url) {
        // 将video_url映射到videoFile字段
        form.value.videoFile = newData.video_url;

        const processedUrl = processVideoUrl(newData.video_url);
        console.log("设置视频URL:", {
          original: newData.video_url,
          processed: processedUrl
        });
        videoUrl.value = processedUrl;
      } else if (newData.videoFile) {
        // 兼容原有的videoFile字段
        const processedUrl = processVideoUrl(newData.videoFile);
        console.log("设置视频URL:", {
          original: newData.videoFile,
          processed: processedUrl
        });
        videoUrl.value = processedUrl;
      } else {
        console.log("清空视频URL");
        videoUrl.value = ""; // 清空预览
      }
    } else {
      // 清空表单数据
      form.value = {
        id: 0,
        exhibitor_id: getExhibitorId() || 0,
        videoName: "",
        videoFile: "",
        video_url: "",
        status: 3
      };
      // 清空视频预览
      videoUrl.value = "";
    }
  },
  { immediate: true, deep: true }
);

// 组件挂载时设置视频上传配置
onMounted(() => {
  // 设置视频上传配置（如果需要调整的话）
  updateUploadConfig(FileType.VIDEO, {
    maxSize: 50 * 1024 * 1024, // 50MB
    maxSizeMB: 50
  });

  // 如果有初始数据，确保视频URL正确设置
  if (
    props.formData &&
    (props.formData.video_url || props.formData.videoFile)
  ) {
    console.log("组件挂载时发现视频数据:", {
      video_url: props.formData.video_url,
      videoFile: props.formData.videoFile
    });
    // 视频URL会在watch中自动设置，这里不需要额外处理
  }
});

// 验证单个字段
const validateField = (fieldName: string) => {
  if (formRef.value) {
    formRef.value.validateField(fieldName);
  }
};

// 视频名称输入处理 - 支持中文、英文、数字、空格、标点符号
const handleVideoNameInput = (value: string) => {
  const filteredValue = value.replace(
    /[^a-zA-Z0-9\u4e00-\u9fa5\s\-\(\)&.,，。！？；：""''（）]/g,
    ""
  );
  form.value.videoName = filteredValue;
};

// 视频名称粘贴处理
const handleVideoNamePaste = (event: ClipboardEvent) => {
  event.preventDefault();
  const pastedText = event.clipboardData?.getData("text") || "";
  const filteredValue = pastedText.replace(
    /[^a-zA-Z0-9\u4e00-\u9fa5\s\-\(\)&.,，。！？；：""''（）]/g,
    ""
  );
  if (filteredValue) {
    form.value.videoName = filteredValue;
  }
};

// 视频名称键盘输入处理
const handleVideoNameKeypress = (event: KeyboardEvent) => {
  const allowedKeys = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "Backspace",
    "Delete",
    "ArrowLeft",
    "ArrowRight",
    "Tab",
    "Enter",
    " ",
    "-",
    "(",
    ")",
    "&",
    ".",
    ",",
    "！",
    "？",
    "；",
    "：",
    "'",
    "'"
  ];

  if (!allowedKeys.includes(event.key)) {
    event.preventDefault();
  }
};

const onSubmit = async () => {
  try {
    // 使用Element Plus表单验证
    if (formRef.value) {
      const valid = await formRef.value.validate();
      if (!valid) {
        ElMessage.error("请检查表单填写是否正确");
        return;
      }
    }

    // 使用自定义验证函数进行额外验证
    const formValidation = validateVideoForm(form.value);
    if (!formValidation.isValid) {
      ElMessage.error(formValidation.errors[0]);
      return;
    }

    // 准备提交数据（更新时需要携带 id）
    const submitData: any = {
      id: form.value.id,
      video_url: form.value.videoFile || form.value.video_url,
      video_name: form.value.videoName,
      exhibitor_id: form.value.exhibitor_id,
      status: form.value.status
    };

    console.log("提交视频数据:", submitData);

    // 根据模式调用不同接口
    let result: any;
    if (props.mode === "add") {
      result = await uploadVideo(submitData);
      if (result.code === 1) {
        ElMessage.success("视频申请成功！");
        emit("confirm", submitData);
      } else {
        ElMessage.error(result.msg || "视频申请失败！");
      }
    } else if (props.mode === "edit") {
      result = await updateVideo(submitData);
      if (result.code === 1) {
        ElMessage.success("视频修改成功！");
        emit("confirm", submitData);
      } else {
        ElMessage.error(result.msg || "视频修改失败！");
      }
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请重试");
  }
};

const fileInput = ref<HTMLInputElement | null>(null);

const triggerFileUpload = () => {
  console.log("触发文件上传，当前状态:", {
    videoUrl: videoUrl.value,
    videoFile: form.value.videoFile,
    mode: props.mode
  });
  fileInput.value?.click();
};

// 视频播放事件处理
const handleVideoError = (event: Event) => {
  console.error("视频播放错误:", event);
  console.error("当前视频URL:", videoUrl.value);

  // 尝试重新设置视频URL
  if (form.value.videoFile && form.value.videoFile !== videoUrl.value) {
    console.log("尝试重新设置视频URL:", form.value.videoFile);
    videoUrl.value = form.value.videoFile;
  } else {
    ElMessage.error("视频播放失败，请检查视频文件");
  }
};

const handleVideoLoadStart = () => {
  console.log("视频开始加载:", videoUrl.value);
};

const handleVideoCanPlay = () => {
  console.log("视频可以播放:", videoUrl.value);
};

const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files ? target.files[0] : null;

  if (!file) return;

  // 清空文件输入，允许重复选择同一文件
  if (target) {
    target.value = "";
  }

  // 使用新的视频文件验证函数
  const videoValidation = validateVideoFile(file);
  if (!videoValidation.isValid) {
    ElMessage.error(videoValidation.errors[0]);
    return;
  }

  try {
    // 生成临时预览URL
    const tempVideoUrl = URL.createObjectURL(file);
    videoUrl.value = tempVideoUrl;

    // 上传视频文件到服务器
    console.log("开始上传视频文件到服务器...");
    const response: any = await uploadVideoFile(file);

    if (response.code === 1) {
      // 服务器返回视频路径
      const serverVideoUrl = response.data;
      console.log("服务器返回的视频路径:", serverVideoUrl);

      // 解析服务器返回的路径
      const videoPath =
        typeof serverVideoUrl === "string"
          ? serverVideoUrl
          : serverVideoUrl.url || serverVideoUrl.full_url || "";

      if (!videoPath) {
        throw new Error("上传失败，未解析到有效的视频地址");
      }

      // 更新表单数据
      form.value.videoFile = videoPath;

      // 清理临时URL，避免内存泄漏
      URL.revokeObjectURL(tempVideoUrl);

      // 更新预览URL为服务器地址
      const processedUrl = processVideoUrl(videoPath);
      console.log("上传成功后设置视频URL:", {
        original: videoPath,
        processed: processedUrl
      });
      videoUrl.value = processedUrl;

      ElMessage.success("视频上传成功");
    } else {
      throw new Error(response.msg || "视频上传失败");
    }
  } catch (error) {
    console.error("视频上传失败:", error);
    ElMessage.error("视频上传失败，请重试");

    // 清理临时URL
    if (videoUrl.value && videoUrl.value.startsWith("blob:")) {
      URL.revokeObjectURL(videoUrl.value);
    }

    // 清空预览和表单数据
    videoUrl.value = "";
    form.value.videoFile = "";
  }
};
</script>

<style lang="scss" scoped>
.ExhibitionInfoForm-container {
  .form {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;

    .title {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 300px;
      height: 50px;
      margin: 40px 0;
      background-color: #f8f9fa;
    }

    .bottom {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;
      color: red;
    }
  }
}

.video-uploader {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 500px;
  height: 200px;
  overflow: hidden;
  background-color: #fff;
  border: 2px solid #e0e0e0;
  border-radius: 6px;
}

.video-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.placeholder-text {
  margin-top: 10px;
  font-size: 14px;
  color: #999;
}

// 查看模式下的输入框样式
:deep(.view-mode-input .el-input__wrapper) {
  cursor: not-allowed !important;
  background-color: #f7f7f7 !important;
  border: 2px solid #e0e0e0 !important;

  .el-input__inner {
    color: #999 !important;
    cursor: not-allowed !important;
    background-color: transparent !important;
  }
}

.video-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.video-preview {
  display: block;
  width: 100%;
  max-height: 200px;
}
</style>
